from django import forms
from apps.web.forms.bootstrap import BootStrapForm
from apps.web import models
from django.core.validators import ValidationError
from apps.web.forms.widgets import ColorRadioSelect


class ProjectModelForm(BootStrapForm, forms.ModelForm):
    bootstrap_class_exclude = ['color']

    # # 重写desc的插件标签
    # desc = forms.CharField(widget=forms.Textarea)

    class Meta:
        # 指定模型类
        model = models.Project
        fields = ['name', 'color', 'desc']
        widgets = {
            'desc': forms.Textarea,
            'color': ColorRadioSelect(attrs={'class': 'color-radio'}),
        }

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    # 定义钩子函数
    def clean_name(self):
        """项目校验"""

        name = self.cleaned_data.get('name')
        # 1.当前用户是否创建了该项目名
        exists = models.Project.objects.filter(name=name, creator=self.request.tracer.user).exists()
        if exists:
            raise ValidationError('项目名已存在')
        # 2.当前用户是否存在额度创建项目
        # 最多能创建多少个项目
        # self.request.tracer.price_policy.project_num
        # 当前用户已经创建了多少个项目
        count = models.Project.objects.filter(creator=self.request.tracer.user).count()
        if count >= self.request.tracer.price_policy.project_num:
            raise ValidationError('项目个数已达到最大值，请购买套餐')
        return name
